package com.woniuxy.hotel.realm;

import java.io.Serializable;
import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.woniuxy.hotel.configuration.ByteSourceUtils;
import com.woniuxy.hotel.user.pojo.User;
import com.woniuxy.hotel.user.service.UserService;

public class UserRealm extends AuthorizingRealm implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -3736864026160747006L;
	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//1.获取 token 中的信息
		String account = (String) principals.getPrimaryPrincipal();
		//2.查询当前用户角色或者权限信息
		Collection<String> roles=userService.showUserRoles(account);
		System.out.println(roles);
		//设置角色
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRoles(roles);
		//设置权限
/*		Set<String> perms = new HashSet<String>();
		perms.add("user:update");
		info.addStringPermissions(perms);*/
		return info;
	}

	// 用户认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String pwd = new String((char[]) token.getCredentials());
		if(pwd.length()==0){
			ByteSource salt =ByteSourceUtils.bytes(token.getPrincipal().toString());
			SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(token.getPrincipal(),new SimpleHash("MD5",pwd, token.getPrincipal(),1024).toString(),salt,getName());
			return info;
		}else{
			// 获取用户提交的账户
			String account = (String) token.getPrincipal();
			User user=userService.findUserByAccount(account);
			if (user == null) {
				return null;
			} else {
				ByteSource salt = ByteSourceUtils.bytes(user.getAccount());
				SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), salt,
						getName());
				return info;
			}
		}
	}
}
